package com.ruoyi.framework.shiro.web.filter.online;

import com.ruoyi.common.constant.ShiroConstants;
import com.ruoyi.framework.shiro.session.OnlineSession;
import com.ruoyi.framework.shiro.session.OnlineSessionDAO;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/*
 *@title OnlineSessionTokenFilter
 *@description
 *@author wanghaohao
 *@version 1.0
 *@create 2025-10-21 17:28
 */
public class OnlineSessionTokenFilter extends AccessControlFilter {
    private OnlineSessionDAO onlineSessionDAO;

    public void setOnlineSessionDAO(OnlineSessionDAO onlineSessionDAO) {
        this.onlineSessionDAO = onlineSessionDAO;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response,
                                      Object object) {
        String isAPI = ((ShiroHttpServletRequest) request).getHeader(ShiroConstants.IS_API_Key);
        if (!ShiroConstants.IS_API.equals(isAPI)) {
            // 不是API请求，返回true
            return true;
        }

        Subject subject = getSubject(request, response);
        if (subject == null || subject.getSession() == null) {
            return true;
        }
        Session session = onlineSessionDAO.readSession(subject.getSession().getId());
        if (session != null && session instanceof OnlineSession) {
            OnlineSession onlineSession = (OnlineSession) session;
            onlineSession.setBrowser(ShiroConstants.WECHAT_MINIPROGRAM);
            onlineSession.setOs(ShiroConstants.WECHAT_MINIPROGRAM_OS);
            request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);

            // 新增：获取并设置User-Agent到request属性
//            String userAgent = ((ShiroHttpServletRequest) request).getHeader("User-Agent");
//            UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
//            SysUser user = ShiroUtils.getSysUser();
//            if (user != null) {
//                onlineSession.setUserId(user.getUserId());
//                onlineSession.setLoginName(user.getLoginName());
//                onlineSession.setAvatar(user.getAvatar());
//                onlineSession.setDeptName(user.getDept().getDeptName());
//                onlineSession.markAttributeChanged();
//            }
//
//            AsyncManager.me().execute(AsyncFactory.syncSessionToDb(onlineSession));
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest,
                                     ServletResponse servletResponse) {
        return false;
    }
}
